package logic

import (
	"alibaba-register/alibabarpc/alibabarpc"
	"alibaba-register/alibabarpc/internal/svc"
	"alibaba-register/models/cache"
	"alibaba-register/models/mysql"
	"alibaba-register/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *alibabarpc.RegisterRequest) (*alibabarpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if get.Val() != in.CaptSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var accountFing mysql.Account
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&accountFing)
	if accountFing.ID != 0 {
		return nil, fmt.Errorf("账号已被注册,请前往登录")
	}

	account := mysql.Account{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Create(&account).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	//删除验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"register"+in.Mobile)
	return &alibabarpc.RegisterResponse{Id: int64(account.ID)}, nil
}
